<template>
  <div>
    <el-button @click="takePhoto">拍照</el-button> <br />
    <video ref="video" width="640" height="480" autoplay></video>
    <canvas ref="canvas" width="640" height="480"></canvas>
    <img ref="photo" />
  </div>
</template>
<script>
export default {
  data() {
    return { video: null, canvas: null, photo: null };
  },
  mounted() {
    this.video = this.$refs.video;
    this.canvas = this.$refs.canvas;
    this.photo = this.$refs.photo;
    navigator.mediaDevices
      .getUserMedia({ video: true })
      .then((stream) => {
        this.video.srcObject = stream;
        this.video.play();
      })
      .catch((error) => {
        console.error("Error accessing camera:", error);
      });
  },
  methods: {
    takePhoto() {
      const context = this.canvas.getContext("2d");
      context.drawImage(
        this.video,
        0,
        0,
        this.canvas.width,
        this.canvas.height
      );
      this.photo.src = this.canvas.toDataURL("image/png");
    },
  },
};
</script>
<style scoped>
canvas {
  display: none;
}
img {
  width: 200px;
  height: auto;
  margin-top: 20px;
}
</style>
